import { createStore } from "vuex";
import { App } from "vue";
import { loginInfo } from "../request/api";
interface MenuObj {
  parentId: number;
  id: number;
  children?: MenuObj[];
}
interface State {
  menus: MenuObj[];
}
interface Newmenus {
  [key: number]: MenuObj;
}
const store = createStore<State>({
  state() {
    return {
      menus: [],
    };
  },
  getters: {
    getNewMenus(state) {
      //旧菜单
      const menus = state.menus;
      console.log(menus[0]);
      const newMenus: Newmenus = {};
      console.log(newMenus);
      menus.forEach((i, index) => {
        if (i.parentId == 0) {
          //一级菜单
          newMenus[i.id] = { ...i, children: newMenus[i.id]?.children || [] };
        } else {
          //二级菜单
          const parentId = i.parentId;
          console.log(newMenus[parentId]);
          newMenus[parentId] = newMenus[parentId] || {};
          // if (!newMenus[parentId]) {
          //   newMenus[i.id] = { ...i };
          // } else {
          newMenus[parentId].children = newMenus[parentId].children || [];
          newMenus[parentId].children?.push(i);
          // }
        }
      });
      return newMenus;
    },
  },
  mutations: {
    updateMenus(state, menus) {
      state.menus = menus;
    },
  },
  actions: {
    getAdminInfo() {
      return new Promise((resolve, reject) => {
        // loginInfo().then((res) => {
        //   if (res.code == 200) {
        //     this.commit("updateMenus", res.data.menus);
        //     resolve(res.data);
        //   } else {
        //     reject(res);
        //   }
        // });
      });
    },
  },
  modules: {},
});
export const initStore = (app: App<Element>) => {
  app.use(store);
};
export default store;
